package com.yc.controller;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yc.CustomException;
import com.yc.R_Code;
import com.yc.Result;
import com.yc.entities.*;
import com.yc.entities.custom.*;
import com.yc.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 患者信息表 前端控制器
 * </p>
 *
 * @author kuakha
 * @since 2021-04-12
 */
@RestController
@Slf4j
@RequestMapping("/bloodSugarPatientInfo")
@Api(value = "BloodSugarPatientInfoController", tags = {"血糖数据信息和患者信息管理和添加患者"})
public class BloodSugarPatientInfoController {

    @Autowired
    private BloodSugarPermissionService bloodSugarPermissionService;
    @Autowired
    private BloodSugarBedService bloodSugarBedService;
    @Autowired
    private BloodSugarDoctorService bloodSugarDoctorService;
    @Autowired
    private BloodSugarPatientInfoService bloodSugarPatientInfoService;
    @Autowired
    private BloodSugarGluceProgramService bloodSugarGluceProgramService;
    @Autowired
    private BloodSugarGluceProgramTempService bloodSugarGluceProgramTempService;
    @Autowired
    private BloodSugarConcernsUserService bloodSugarConcernsUserService;
    @Autowired
    private BloodSugarGluceService bloodSugarGluceService;


    @ApiOperation(value = "pc查询科室下面的所有医生信息 暂无用处")
    @PreAuthorize("hasAnyAuthority('sys:index')")
    @GetMapping("getAllDoctorInfo/{departmentId}/")
    public Result getAllDoctorInfo(@ApiParam(name = "departmentId", value = "科室id") @NotNull(message = "科室id不能为空") @PathVariable Integer departmentId) {
        LambdaQueryWrapper<BloodSugarDoctor> departmentLambdaQueryWrapper = Wrappers.lambdaQuery();
        departmentLambdaQueryWrapper.eq(BloodSugarDoctor::getDepartmentId, departmentId);
        List<BloodSugarDoctor> list = bloodSugarDoctorService.list(departmentLambdaQueryWrapper);
        return Result.ok().data(list);
    }

    @ApiOperation(value = "pc查看所有权限菜单 角色管理分配角色权限使用")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @PostMapping("getAllPermissionInfo")
    public Result getAllPermissionInfo() {
        //需要传入院长id
        List<BloodSugarPermission> list = bloodSugarPermissionService.list();
        if (list.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("pcMenu", list.stream().filter(f1 -> ("0".equals(f1.getClientType()))).filter(f1 -> f1.getParentId() == 0).collect(Collectors.toList()));
            map.put("appMenu", list.stream().filter(f1 -> "1".equals(f1.getClientType())).collect(Collectors.toList()));
            return Result.ok().data(map);
        } else {
            return Result.ok().code(R_Code.R_NULL_DATA_FAIL);
        }
    }


    @ApiOperation(value = "pc查询添加患者时的床位 根据院长id和科室id")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getAllBedNum")
    public Result getAllBedNum(@ApiParam(name = "deanId", value = "院长id") @RequestParam Integer deanId,
                               @ApiParam(name = "departmentId", value = "科室id") @RequestParam Integer departmentId,
                               @ApiParam(name = "current", value = "当前页码") @RequestParam(required = false) Integer current,
                               @ApiParam(name = "size", value = "一页显示多少条") @RequestParam(required = false) Integer size) {
        return bloodSugarBedService.getAllBedNum(deanId, departmentId, current, size);
    }

    @ApiOperation(value = "pc查询修改患者时的床位 根据院长id和科室id 下拉框使用")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getAllBedNumBox")
    public Result getAllBedNumBox(@ApiParam(name = "deanId", value = "院长id") @RequestParam Integer deanId,
                                  @ApiParam(name = "departmentId", value = "科室id") @RequestParam Integer departmentId) {
        return bloodSugarBedService.getAllBedNumBox(deanId, departmentId);
    }

    @ApiOperation(value = "pc添加患者信息")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @PostMapping("addPatientInfo")
    public Result addPatientInfo(@Valid @RequestBody CustomPatientSaveRequestBean customPatientSaveRequestBean) {
        if (customPatientSaveRequestBean.getBrithday() == null) {
            throw new CustomException(400, "用户出生日期不能为空");
        }
        if (customPatientSaveRequestBean.getToHospitalTime() == null) {
            throw new CustomException(400, "用户入院时间不能为空");
        }
        //查看患者是否已经住院
        LambdaQueryWrapper<BloodSugarPatientInfo> lambdaQuery1 = Wrappers.lambdaQuery();
        lambdaQuery1.eq(BloodSugarPatientInfo::getHospitalNum, customPatientSaveRequestBean.getHospitalNum())
                .eq(BloodSugarPatientInfo::getTheHospitalStatus, "0");
        List<BloodSugarPatientInfo> list1 = bloodSugarPatientInfoService.list(lambdaQuery1);
        if (list1.size() > 0) {
            return Result.error().code(R_Code.R_ADD_FAIL).message("该患者已经住院");
        }
        //查看床位是否存在
        LambdaQueryWrapper<BloodSugarBed> lambdaQueryBed = Wrappers.lambdaQuery();
        lambdaQueryBed.eq(BloodSugarBed::getId, customPatientSaveRequestBean.getBedId());
        BloodSugarBed one = bloodSugarBedService.getOne(lambdaQueryBed);
        if (one == null) {
            return Result.error().code(R_Code.R_ADD_FAIL).message("该床位不存在,请重新选择");
        } else {
            if (one.getUserId() != 0) {
                return Result.error().code(R_Code.R_ADD_FAIL).message("该床位已经被占用,请重新选择");
            }
        }
        int status = bloodSugarPatientInfoService.savePatientInto(customPatientSaveRequestBean);
        List<BloodSugarGluceProgram> bloodSugarGlucePrograms = bloodSugarGluceProgramTempService.bloodSugarGlucePrograms(customPatientSaveRequestBean.getSugarType());
        if (CollectionUtil.isNotEmpty(bloodSugarGlucePrograms)) {
            bloodSugarGlucePrograms.forEach(bloodSugarGluceProgram -> {
                bloodSugarGluceProgram.setProgramGlUserid(customPatientSaveRequestBean.getId());
            });
        }
        LambdaUpdateWrapper<BloodSugarBed> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(BloodSugarBed::getId, customPatientSaveRequestBean.getBedId()).set(BloodSugarBed::getUserId, customPatientSaveRequestBean.getId());
        boolean update = bloodSugarBedService.update(updateWrapper);
        boolean b = bloodSugarGluceProgramService.saveBatch(bloodSugarGlucePrograms);
        if (status > 0 && b && update) {
            return Result.ok();
        } else {
            return Result.error().code(R_Code.R_ADD_FAIL);
        }
    }

    @ApiOperation(value = "pc修改患者信息")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @PostMapping("updatePatientInfo")
    public Result updatePatientInfo(@Valid @RequestBody BloodSugarPatientInfo bloodSugarPatientInfo) {
        //查看床位是否存在
        LambdaQueryWrapper<BloodSugarBed> lambdaQueryBed = Wrappers.lambdaQuery();
        lambdaQueryBed.eq(BloodSugarBed::getId, bloodSugarPatientInfo.getBedId());
        BloodSugarBed one = bloodSugarBedService.getOne(lambdaQueryBed);
        if (one == null) {
            return Result.error().code(R_Code.R_ADD_FAIL).message("该床位不存在,请重新选择");
        } else {
            if (!one.getId().equals(bloodSugarPatientInfo.getBedId())) {
                if (one.getUserId() != 0) {
                    LambdaQueryWrapper<BloodSugarBed> lambdaQuery = Wrappers.lambdaQuery();
                    lambdaQuery.eq(BloodSugarBed::getUserId, bloodSugarPatientInfo.getId());
                    BloodSugarBed one1 = bloodSugarBedService.getOne(lambdaQuery);
                    if (!one1.getId().equals(bloodSugarPatientInfo.getBedId())) {
                        return Result.error().code(R_Code.R_ADD_FAIL).message("该床位已经被占用,请重新选择");
                    }
                }
            }
        }
        LambdaUpdateWrapper<BloodSugarConcernsUser> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(BloodSugarConcernsUser::getUserId,bloodSugarPatientInfo.getId())
                .set(BloodSugarConcernsUser::getDoctorId,bloodSugarPatientInfo.getDoctorId());
        bloodSugarConcernsUserService.update(lambdaUpdateWrapper);
        boolean status = bloodSugarPatientInfoService.updateById(bloodSugarPatientInfo);
        LambdaUpdateWrapper<BloodSugarBed> updateWrapper1 = Wrappers.lambdaUpdate();
        updateWrapper1.eq(BloodSugarBed::getUserId, bloodSugarPatientInfo.getId()).set(BloodSugarBed::getUserId, 0);
        boolean update1 = bloodSugarBedService.update(updateWrapper1);
        if (update1) {
            LambdaUpdateWrapper<BloodSugarBed> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(BloodSugarBed::getId, bloodSugarPatientInfo.getBedId()).set(BloodSugarBed::getUserId, bloodSugarPatientInfo.getId());
            boolean update = bloodSugarBedService.update(updateWrapper);
            if (status && update) {
                return Result.ok();
            } else {
                return Result.error().code(R_Code.R_UPDATE_FAIL);
            }
        }
        return Result.error().code(R_Code.R_UPDATE_FAIL);
    }

    @ApiOperation(value = "pc查看首页信息")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @PostMapping("getIndexUserInfo")
    public Result getIndexUserInfo(@Valid @RequestBody CustomIndexQueryRequestBean customIndexQueryRequestBean) {
        return bloodSugarPatientInfoService.getAllIndexInfo(customIndexQueryRequestBean);
    }

    @Transactional(rollbackFor = Exception.class)
    @ApiOperation(value = "pc关注用户")
    @GetMapping("attentionUser")
    public Result attentionUser(@ApiParam(value = "患者id") @RequestParam Integer userId,
                                @ApiParam(value = "医生Id") @RequestParam Integer doctorId) {
        LambdaQueryWrapper<BloodSugarConcernsUser> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(BloodSugarConcernsUser::getDoctorId, doctorId);
        lambdaQuery.eq(BloodSugarConcernsUser::getUserId, userId);
        BloodSugarConcernsUser bloodSugarConcernsUser = bloodSugarConcernsUserService.getOne(lambdaQuery);
        if (bloodSugarConcernsUser != null) {
            boolean b = bloodSugarConcernsUserService.removeById(bloodSugarConcernsUser.getId());
            if (b) {
                return Result.ok().message("取消关注成功");
            } else {
                return Result.error().message("取消关注失败");
            }
        } else {
            BloodSugarConcernsUser saveConcernsUser = new BloodSugarConcernsUser();
            saveConcernsUser.setDoctorId(doctorId);
            saveConcernsUser.setUserId(userId);
            saveConcernsUser.setCreateTime(new Date());
            boolean save = bloodSugarConcernsUserService.save(saveConcernsUser);
            if (save) {
                return Result.ok().message("关注成功");
            } else {
                return Result.error().message("关注失败");
            }
        }
    }

    @ApiOperation(value = "pc患者出院")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("updatePatientOutHospital")
    public Result updatePatientOutHospital(@ApiParam(name = "id", value = "患者id") @NotNull(message = "患者id不能为空") @RequestParam Integer id/*,
                                        @ApiParam(name = "outSugarNum", value = "出院血糖值") @RequestParam Double outSugarNum*/) {

        LambdaQueryWrapper<BloodSugarGluce> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(BloodSugarGluce::getGluceUserid, id).orderByDesc(BloodSugarGluce::getGluceExamtime);
        List<BloodSugarGluce> list = bloodSugarGluceService.list(lambdaQuery);
        if (list.size() > 0) {
            LambdaUpdateWrapper<BloodSugarBed> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.eq(BloodSugarBed::getUserId, id).set(BloodSugarBed::getUserId, 0);
            boolean update = bloodSugarBedService.update(updateWrapper);
            BigDecimal gluceValue = list.get(0).getGluceValue();
            LambdaUpdateWrapper<BloodSugarPatientInfo> updateWrapper1 = Wrappers.lambdaUpdate();
            updateWrapper1.eq(BloodSugarPatientInfo::getId, id)
                    .set(BloodSugarPatientInfo::getTheHospitalStatus, "1")
                    .set(BloodSugarPatientInfo::getOutSugarNum, gluceValue.doubleValue())
                    .set(BloodSugarPatientInfo::getOutHospitalTime, new Date());
            boolean update1 = bloodSugarPatientInfoService.update(updateWrapper1);
            if (update && update1) {
                return Result.ok().message("出院成功");
            } else {
                return Result.error().message("出院失败");
            }
        }
        return Result.error().message("该患者还没有测量过血糖值");

    }

    @ApiOperation(value = "pc更新患者控糖目标值")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @PostMapping("updatePatientTargetValues")
    public Result updatePatientTargetValues(@RequestBody List<BloodSugarGluceProgram> bloodSugarGlucePrograms) {
        boolean update = bloodSugarGluceProgramService.updateBatchById(bloodSugarGlucePrograms);
        if (update) {
            return Result.ok();
        } else {
            return Result.error().code(R_Code.R_UPDATE_FAIL);
        }
    }

    @ApiOperation(value = "pc更新患者控糖目标")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @PostMapping("updatePatientTarget")
    public Result updatePatientTarget(@ApiParam(name = "targetId", value = "控糖目标id") @NotNull(message = "控糖目标id") @RequestParam Integer targetId,
                                      @ApiParam(name = "option", value = "修改状态 0 未选择 1 已选择") @NotNull(message = "修改状态不能为空") @RequestParam String option) {
        LambdaUpdateWrapper<BloodSugarGluceProgram> lambdaUpdateWrapper = Wrappers.lambdaUpdate();
        lambdaUpdateWrapper.eq(BloodSugarGluceProgram::getId, targetId).set(BloodSugarGluceProgram::getProgramGlOption, option);
        boolean update = bloodSugarGluceProgramService.update(lambdaUpdateWrapper);
        if (update) {
            return Result.ok();
        } else {
            return Result.error().code(R_Code.R_UPDATE_FAIL);
        }
    }

    @ApiOperation(value = "pc添加血糖记录")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("addGlucoseRecord")
    public Result addGlucoseRecord(@ApiParam(name = "userId", value = "患者id") @RequestParam String userId,
                                   @ApiParam(name = "attr", value = "测量时间段") @RequestParam String attr,
                                   @ApiParam(name = "sugarValue", value = "血糖值") @RequestParam String sugarValue,
                                   @ApiParam(name = "examTime", value = "操作时间") @RequestParam String examTime) {
        return bloodSugarGluceService.insertSugarDataByUser(userId, attr, sugarValue, examTime);
    }

    @ApiOperation(value = "pc查询首页患者详细信息中  基本信息数据")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getIndexUserBaseInfoById/id/{id}")
    public Result getIndexUserBaseInfoById(@ApiParam(name = "id", value = "患者id") @NotNull(message = "患者id不能为空") @PathVariable Integer id) {
        LambdaQueryWrapper<BloodSugarGluceProgram> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(BloodSugarGluceProgram::getProgramGlUserid, id);
        CustomPatientInfoResponseBean bloodSugarPatientInfo = bloodSugarPatientInfoService.getPatientById(id);
        List<BloodSugarGluceProgram> bloodSugarGlucePrograms = bloodSugarGluceProgramService.list(lambdaQueryWrapper);
        if (bloodSugarPatientInfo != null && bloodSugarGlucePrograms != null) {
            Result ok = Result.ok();
            ok.data("bloodSugarPatientInfo", bloodSugarPatientInfo).data("bloodSugarGluceProgram", bloodSugarGlucePrograms);
            return ok;
        } else {
            return Result.error().message("患者信息获取失败");
        }
    }

    @ApiOperation(value = "pc查询数据管理  基本信息数据")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getDataUserBaseInfoById/id/{id}")
    public Result getDataUserBaseInfoById(@ApiParam(name = "id", value = "患者id") @NotNull(message = "患者id不能为空") @PathVariable Integer id) {
        LambdaQueryWrapper<BloodSugarGluceProgram> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(BloodSugarGluceProgram::getProgramGlUserid, id);
        CustomPatientInfoResponseBean bloodSugarPatientInfo = bloodSugarPatientInfoService.getPatientById(id);
        if (bloodSugarPatientInfo != null) {
            return Result.ok().data(bloodSugarPatientInfo);
        } else {
            return Result.error().message("患者信息获取失败");
        }
    }

    @ApiOperation(value = "pc查询首页患者详细信息中  编辑基本数据查询")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getIndexUserBaseInfoDetail/{id}")
    public Result getIndexUserBaseInfoDetail(@ApiParam(name = "id", value = "患者id") @NotNull(message = "患者id不能为空") @PathVariable Integer id) {
        BloodSugarPatientInfo bloodSugarPatientInfo = bloodSugarPatientInfoService.getById(id);
        if (bloodSugarPatientInfo != null) {
            return Result.ok().data(bloodSugarPatientInfo);
        } else {
            return Result.error().message("患者信息获取失败");
        }
    }

    @ApiOperation(value = "pc查询首页患者详细  血糖数据查询")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getIndexUserBloodGlucoseInfo")
    public Result getIndexUserBloodGlucoseInfo(@ApiParam(name = "id", value = "患者id") @RequestParam Integer id,
                                               @ApiParam(name = "startTime", value = "起始时间") @RequestParam(required = false) String startTime,
                                               @ApiParam(name = "endTime", value = "结束时间") @RequestParam(required = false) String endTime,
                                               @ApiParam(name = "current", value = "当前页码") @RequestParam(required = false) Integer current,
                                               @ApiParam(name = "size", value = "一页显示多少条") @RequestParam(required = false) Integer size) {
        return bloodSugarPatientInfoService.getIndexUserBloodGlucoseInfo(id, current, size, startTime, endTime);
    }

    @ApiOperation(value = "pc查询数据管理  折线图信息")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getDataUserLineChartInfo")
    public Result getDataUserLineChartInfo(@ApiParam(name = "id", value = "患者id") @RequestParam Integer id,
                                           @ApiParam(name = "startTime", value = "起始时间") @RequestParam(required = false) String startTime,
                                           @ApiParam(name = "endTime", value = "结束时间") @RequestParam(required = false) String endTime) {
        return bloodSugarPatientInfoService.getDataUserLineChartInfo(id, startTime, endTime);
    }


    @ApiOperation(value = "pc查询首页患者详细  血糖数据详情查询")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getIndexUserBloodGlucoseDetail")
    public Result getIndexUserBloodGlucoseDetail(@ApiParam(name = "id", value = "患者id") @RequestParam Integer id,
                                                 @ApiParam(name = "time", value = "起始时间") @RequestParam String time,
                                                 @ApiParam(name = "attr", value = "测量血糖时间段") @RequestParam String attr) {
        return bloodSugarPatientInfoService.getIndexUserBloodGlucoseDetail(id, time, attr);
    }


    @ApiOperation(value = "pc查询首页患者详细  出入院记录")
    @PreAuthorize("hasAnyAuthority('sys:index','sys:noAccess')")
    @GetMapping("getIndexUserOutInHospitalRecord")
    public Result getIndexUserOutInHospitalRecord(@ApiParam(name = "hospitalNum", value = "住院号") @RequestParam String hospitalNum,
                                                  @ApiParam(name = "current", value = "当前页码") @RequestParam(required = false) Integer current,
                                                  @ApiParam(name = "size", value = "一页显示多少条") @RequestParam(required = false) Integer size) {
        return bloodSugarPatientInfoService.getIndexUserOutInHospitalRecord(hospitalNum, current, size);
    }

    @ApiOperation(value = "pc查看所有数据管理信息")
    @PreAuthorize("hasAnyAuthority('sys:dataManage','sys:noAccess')")
    @PostMapping("getAllDataInfo")
    public Result getAllDataInfo(@Valid @RequestBody CustomDataQueryRequestBean customDataQueryRequestBean) {
        return bloodSugarPatientInfoService.getAllDataInfo(customDataQueryRequestBean);
    }

}

